package com.tcm.smarthealth.service.ai;

import com.tcm.smarthealth.enums.ImageAnalysisType;
import com.tcm.smarthealth.enums.QuestionType;
import reactor.core.publisher.Flux;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class MockAiClient implements AiClient {

    @Override
    public AiInsight generateQuestionInsight(String question, QuestionType type) {
        AiInsight insight = new AiInsight();
        insight.setAnswer("【模拟建议】根据您描述的情况，请保持良好作息，并咨询专业医师以获得更精准的诊断建议。");
        insight.setSuggestions(List.of("保持规律作息，避免熬夜", "注意饮食均衡，多饮温水"));
        insight.setConfidence(randomConfidence(type == QuestionType.HYBRID ? 0.85 : 0.8));
        return insight;
    }

    @Override
    public AiInsight analyzeImage(byte[] imageBytes, String filename, ImageAnalysisType type) {
        AiInsight insight = new AiInsight();
        switch (type) {
            case TONGUE_DIAGNOSIS:
                insight.setDiagnosis("舌苔略黄，建议关注脾胃调理。");
                insight.setSuggestions(List.of("多饮温水，少食辛辣", "保证充足睡眠"));
                break;
            case WOUND_ASSESSMENT:
                insight.setDiagnosis("创口处略有红肿，建议保持清洁并观察变化。");
                insight.setSuggestions(List.of("使用无菌敷料，并每日更换", "如疼痛加剧请及时就医"));
                break;
            case SKIN_CONDITION:
            default:
                insight.setDiagnosis("皮肤轻度干燥，建议适度保湿和防晒。");
                insight.setSuggestions(List.of("使用温和型保湿产品", "减少在强光下长时间暴露"));
                break;
        }
        insight.setConfidence(randomConfidence(0.82));
        return insight;
    }

    @Override
    public Flux<String> streamQuestionAnswer(String question, QuestionType type) {
        AiInsight insight = generateQuestionInsight(question, type);
        String answer = insight.getAnswer();
        if (answer == null || answer.isEmpty()) {
            answer = "请在专业医生指导下进行进一步诊断。";
        }
        String[] segments = answer.split("(?<=。|！|？|\n)");
        return Flux.fromArray(segments)
                .map(String::trim)
                .filter(segment -> !segment.isEmpty());
    }

    private BigDecimal randomConfidence(double base) {
        double value = ThreadLocalRandom.current().nextDouble(base, Math.min(base + 0.12, 0.99));
        return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP);
    }
}

